<template>
	<view class="page">
		<view class="main">
			<view class="sider hide-scroller-bar">
				<SideBar v-model="sideBarIndex" @change="onCategoryChange" />
			</view>
			<view class="content hide-scroller-bar">
				<view class="content-date">
					<text>{{ menuDate }}</text>
				</view>
				<DishCard
					v-for="item in dishesList"
					:key="item.id"
					:data="item"
					@edit="onEditDishes"
					@delete="onDeleteDishes"
				>
					<button
						v-if="ctl.isSelected(item.id)"
						class="card-btn"
						plain="true"
						size="mini"
					>
						已选
					</button>

					<button
						v-else
						class="card-btn"
						plain="true"
						type="primary"
						size="mini"
						@tap="onAddDishesToMenu(item)"
					>
						添加
					</button>
				</DishCard>
			</view>
		</view>

		<view class="buttom">
			<DishesCart
				:data="dishesListInCart"
				@delete="onDeleteDishesFromCart"
				@confirm="onUpdateMenu"
			/>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';

import { useController } from './controller.js';
import SideBar from './SideBar.vue';
import { showConfirmDialog, showDialog } from '../../hooks/useConfirm.js';

const { menuDate, sideBarIndex, dishesList, dishesListInCart, ...ctl } = useController();

const onCategoryChange = () => {
	ctl.setDishesListByCategory();
};

onLoad((event) => {
	console.log('onLoad event:', event.date);
	menuDate.value = event.date;
	ctl.getMenu();
});

// 添加菜品到菜单
const onAddDishesToMenu = (data) => {
	ctl.addDishesToMenu(data);
};

// 移除菜单中的菜品
const onDeleteDishesFromCart = (dishes) => {
	console.log('移除菜单中的菜品', dishes);
	ctl.removeDishesFromCartList(dishes.id);
};

// 修改菜品
const onEditDishes = (date) => {
	console.log('onEditDishes', date);
	uni.navigateTo({
		url: '/pages/update-dishes/update-dishes' + `?id=${date.id}`,
	});
};

// 删除菜品
const onDeleteDishes = async (dishes) => {
	console.log('onDeleteDishes');
	const confirm = await showDialog({ title: '删除', content: `确定删除"${dishes.name}"吗？` });
	if (!confirm) return;

	await ctl.deleteDishes(dishes.id);
	showConfirmDialog({ title: '成功', content: `删除"${dishes.name}"成功` });

	ctl.setDishesListByCategory();
};

// 设置菜单
const onUpdateMenu = async () => {
	await ctl.updateMenu();
	await showConfirmDialog({ title: '成功', content: '设置菜单成功' });
	uni.navigateBack();
};
</script>

<style scoped>
.page {
	display: flex;
	flex-direction: column;

	height: 100%;
	width: 100%;
}

.main {
	flex: 1;
	display: flex;
	height: calc(100% - 100rpx);
}

.sider {
	height: 100%;
	background-color: #f8f8f8;
	overflow: auto;
}

.content {
	flex: 1;
	height: 100%;
	overflow: auto;
}

.content-date {
	padding: 12rpx;
	color: #444;
	font-weight: bold;
}

.buttom {
	height: 100rpx;
}
</style>
